const express = require('express')
const router = express.Router()
const { db, genid } = require('../db/DbUtils')

//列表接口，查询所有的分类名
router.get('/list', async (req, res) => {
  const search_sql = 'SELECT * FROM  `category`'
  let { err, rows } = await db.async.all(search_sql, [])
  if (err == null) {
    res.send({
      code: 200,
      msg: '查询成功',
      rows,
    })
  } else {
    res.send({
      code: 500,
      msg: '查询失败',
      detail: err,
    })
  }
})

//添加接口
router.post('/_token/add', async (req, res) => {
  let { name } = req.body
  //   先查询表中有没有相同的分类名
  let search_sql = 'SELECT * FROM `category` WHERE name = ?'
  let { err, rows } = await db.async.all(search_sql, [name])
  //   如果查询结果没有错误且长度不为0,即存在相同分类名
  if (err == null && rows.length != 0) {
    res.send({
      code: 500,
      msg: '分类名已存在',
    })
  } else {
    // 如果表中没有相同的分类名则执行插入语句
    const insert_sql = 'INSERT INTO `category` (`id`,`name`) VALUES (?,?)'
    let { err, rows } = await db.async.run(insert_sql, [genid.NextId(), name])
    if (err == null) {
      res.send({
        code: 200,
        msg: '添加成功',
      })
    } else {
      res.send({
        code: 500,
        msg: '添加失败',
        detail: err,
      })
    }
  }
})

//修改接口
router.put('/_token/update', async (req, res) => {
  let { id, name } = req.body
  const update_sql = 'UPDATE `category` SET `name` = ? WHERE `id` = ?'
  let { err, rows } = await db.async.run(update_sql, [name, id])
  if (err == null) {
    res.send({
      code: 200,
      msg: '修改成功',
    })
  } else {
    res.send({
      code: 500,
      msg: '修改失败',
      detail: err,
    })
  }
})

//删除接口  /category/delete?id=xxx
router.delete('/_token/delete', async (req, res) => {
  let id = req.query.id
  const delete_sql = 'DELETE FROM `category` WHERE `id` = ?'
  let { err, rows } = await db.async.run(delete_sql, [id])
  //删除成功的返回值{ err: null, rows: undefined }
  if (err == null && rows == undefined) {
    res.send({
      code: 200,
      msg: '删除成功',
    })
  } else {
    res.send({
      code: 500,
      msg: '删除失败',
      detail: err,
    })
  }
})

module.exports = router
